//实现一个翻译服务器，客户端发送一个单词，返回一个汉语

#include<muduo/net/TcpServer.h>
#include<muduo/net/EventLoop.h>
#include<muduo/net/Buffer.h>
#include<muduo/net/TcpConnection.h>
#include<muduo/net/InetAddress.h>
#include<iostream>
#include<unordered_map>
#include<functional>
class DictServer
{
public:
   DictServer(int port) :_server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port), "DictServer",
       muduo::net::TcpServer::Option::kReusePort)
   {

// typedef std::shared_ptr<TcpConnection> TcpConnectionPtr;
// typedef std::function<void()> TimerCallback;
// typedef std::function<void (const TcpConnectionPtr&)> ConnectionCallback;
// typedef std::function<void (const TcpConnectionPtr&)> CloseCallback;
// typedef std::function<void (const TcpConnectionPtr&)> WriteCompleteCallback;
// typedef std::function<void (const TcpConnectionPtr&, size_t)> HighWaterMarkCallback;  
        //function<void (const TcpConnectionPtr&)> cb = std::bind(&DictServer::onConnection, this, std::placeholders::_1)
       _server.setConnectionCallback(std::bind(&DictServer::onConnection, this, std::placeholders::_1));
       _server.setMessageCallback(std::bind(&DictServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
   }
   void start()
   {
       _server.start();
       _baseloop.loop();
   }

private:

   void onConnection(const muduo::net::TcpConnectionPtr& con)
   {
       if (con.get())
       {
           std::cout << "连接成功" << std::endl;
       }
       else {
           std::cout << "连接断开" << std::endl;
       }
   }
   void onMessage(const muduo::net::TcpConnectionPtr& conn,
       muduo::net::Buffer* buf,
       muduo::Timestamp t)
   {
       std::string msg = buf->retrieveAllAsString();//获取里面的字符
       std::unordered_map<std::string, std::string> dictmap = {
           {"apple","苹果"},
           {"hello","你好"},
           {"world","世界"}
       };
       auto n = dictmap.find(msg);
       if (n == dictmap.end())
       {
           conn->send("未知单词");
       }
       else {
           conn->send(n->second);
       }

   }

private:
   muduo::net::EventLoop _baseloop;
   muduo::net::TcpServer _server;
};
int main()
{
   DictServer server(8080);
   server.start();
   return 0;
}
